import sequence from '@/util/sequence';
import queryUtil from '@/util/queryUtil';

/**
 * 密码服务
 *
 * @author 猴哥
 */
class PasswordService {
	/**
	 * 获取密码列表
	 *
	 * @param pageNum 页码
	 * @param pageSize 条数
	 * @param passwordName 名称
	 */
	getList(pageNum, pageSize, passwordName) {
		let passwordList = this.getPasswordList()
			.filter(password => {
				// 过滤查询条件
				if (passwordName && passwordName !== '') {
					return password.passwordName.toUpperCase().indexOf(passwordName.toUpperCase()) !== -1;
				}
				return true;
			});
		// 总条数
		let total = passwordList.length;
		// 排序
		passwordList = queryUtil.orderByDesc(passwordList, 'passwordId');
		// 分页
		passwordList = queryUtil.getPage(passwordList, pageNum, pageSize);
		// 封装结果
		return {
			list: passwordList,
			total
		};
	}

	/**
	 * 添加密码
	 *
	 * @param password 密码
	 */
	add(password) {
		// 获取密码id
		password.passwordId = sequence('passwordId');
		// 获取密码列表
		let passwordList = this.getPasswordList();
		// 进行添加
		passwordList.push(password);
		uni.setStorageSync('passwordList', passwordList);
	}

	/**
	 * 修改密码
	 *
	 * @param password 密码
	 */
	update(password) {
		// 获取密码列表
		let passwordList = this.getPasswordList()
			// 进行修改
			.map(oldPassword => oldPassword.passwordId === password.passwordId ? password : oldPassword);
		// 重新存进去
		uni.setStorageSync('passwordList', passwordList);
	}

	/**
	 * 获取密码列表
	 *
	 * @returns {Array} 密码列表
	 */
	getPasswordList() {
		let passwordList = uni.getStorageSync('passwordList');
		return passwordList === '' ? [] : passwordList;
	}

	/**
	 * 删除密码
	 *
	 * @param passwordId 密码id
	 */
	del(passwordId) {
		let passwordList = uni.getStorageSync('passwordList')
			.filter(password => password.passwordId !== passwordId);
		uni.setStorageSync('passwordList', passwordList);
	}

	/**
	 * 导入所有数据
	 *
	 * @param passwordList 所有密码
	 */
	importAll(passwordList) {
		uni.setStorageSync('passwordList', passwordList);
	}
}
module.exports = new PasswordService();
